import { userInfo } from 'os'
import { Body, Injectable } from '@nestjs/common'
import { UsersService } from '../users/users.service'
import { JwtService } from '@nestjs/jwt'
import { enCode } from 'src/utils'
import { UserInfoService } from 'src/user-info/user-info.service'
import { BusinessException } from 'src/common/exceptions/business.exception'
import { User } from 'src/entity/User'
import { Connection, IsNull } from 'typeorm'
import { UserInfo } from 'src/entity/Userinfo'

@Injectable()
export class AuthService {
  constructor(
    private readonly usersService: UsersService,
    private readonly userInfoService: UserInfoService,
    private readonly jwtService: JwtService,
    private connection: Connection,
  ) { }

  // 用户登录验证并返回JWT
  async validateUser(userName: string, pass: string): Promise<any> {
    const user = await this.usersService.findOne(userName)
    if (user && user.password === enCode(pass)) {
      const data = await this.setJwt(user)
      return data
    }
    throw new BusinessException('账号或者密码错误')
  }

  // 设置JWT token
  async setJwt(user: User) {
    const payload = { userName: user.userName, sub: user.id }
    // const userInfo = await this.usersService.findOne(user.userName)
    const token = this.jwtService.sign(payload)
    // console.log('verify', this.jwtService.verify(token))
    const data = {
      token: token,
      refreshToken: 'todo',
      // 过期时间，和jwt过期时间一致
      expiresIn: 20 * 60 * 1000,
      userId: user.id,
    }
    return data
  }
  // 获取用户信息
  getUserInfo(userId: number) {
    console.log('userId', userId)
    if (userId === undefined || userId === null)
      throw new BusinessException('请求参数错误')

    return this.userInfoService.findOne(userId)
  }
  // 注册用户
  register(data) {
    return this.userInfoService.register(data)
  }
  // 删除用户
  delete(id) {
    return this.userInfoService.delete(id)
  }
  // 更新用户信息
  update(userInfo) {
    return this.userInfoService.update(userInfo)
  }
  // 获取用户信息列表
  async pages({ pageRequest: { pageIndex, pageSize }, orgId }) {
    let resData
    await this.connection.transaction(async (manager) => {
      const sqlAllData = await manager.find(UserInfo, {
        where: {
          isDelete: IsNull(),
        },
      })

      const sqlData = await manager.find(UserInfo, {
        where: {
          isDelete: IsNull(),
        },
        skip: (pageIndex - 1) * pageSize,
        take: pageSize,
        withDeleted: false,
      })
      resData = {
        content: sqlData.map((item) => {
          return {
            ...item,
            orgId: item.orgId.toString(),
          }
        }),
        total: sqlAllData.length,
      }
    })
    return resData
  }

  // 修改用户信息
  async edit(data) {
    await this.connection.transaction(async (manager) => {
      await manager.update(
        UserInfo,
        {
          userId: data.userId,
        },
        data,
      )
    })
    return {}
  }

  // 修改用户密码
  async editPassword({ id, password }) {
    await this.connection.transaction(async (manager) => {
      await manager.update(
        User,
        {
          id,
        },
        {
          password: enCode(password),
        },
      )
    })
    return {}
  }
}
